<template>
  <div class="home">
    <div class="nav">
      <div class="top">
        <!-- <div class="logo"></div> -->
        <h1>猫眼电影</h1>
        <!-- <div class="nav-botton">
          <i class="iconfont icon-danlieliebiao"></i>
        </div> -->
      </div>
      <div class="tab">
        <div class="location">
          <router-link to="city">
            <span>{{city}}</span>
            <i class="iconfont icon-zelvxuanzefeiyongdaosanjiaoxingfandui"></i>
          </router-link>
        </div>
        <van-tabs v-model="active" swipeable line-width="25px" line-height="2px" title-inactive-color="#888" title-active-color="#000">
          <van-tab title="热映"></van-tab>
          <van-tab title="影院"></van-tab>
          <van-tab title="待映"></van-tab>
          <van-tab title="经典电影"></van-tab>
        </van-tabs>
        <div class="search">
          <!-- <i class="iconfont icon-sousuo"></i> -->
        </div>
      </div>
    </div>
    <div class="movie" v-if="active==0">
      <div class="good-movie" v-if="ratedMovies">
        <list-title v-if="title.length>0">{{title}}</list-title>
        <ul class="imgBox">
          <li v-for="item in ratedMovies" :key="item.movieId">
            <router-link :to="`/moviedetial/${item.movieId}`">
              <img-item :item="item"></img-item>
            </router-link>
          </li>
        </ul>
      </div>
      <div class="bt-line" v-if="ratedMovies"></div>
      <ol class="movieList" ref="moviebox" v-if="movieList">
        <li v-for="movie in movieList" :key="movie.id">
          <router-link :to="`/moviedetial/${movie.id}`">
            <movie-list :movie="movie"></movie-list>
          </router-link>
        </li>
      </ol>
      <loading-animation v-if="isload" :showText="true"></loading-animation>
      <div class="bt-line" v-if="movieList && movieList.length>0 && movieList.length>=movieIds.length"></div>
    </div>

    <div class="cinema" v-else-if="active==1"> 
      <van-dropdown-menu>
        <van-dropdown-item :title="areaName" ref="item1">
          <van-tabs v-model="choose">
            <van-tab title="商区">
              <van-tree-select
                :items="items"
                :active-id.sync="activeId"
                :main-active-index.sync="activeIndex"
                @click-nav="clnav" @click-item="clitem"
              />
            </van-tab>
            <van-tab title="地铁站" :disabled="items2.length==0">
              <van-tree-select
                :items="items2"
                :active-id.sync="active2Id"
                :main-active-index.sync="active2Index"
                @click-nav="clnav2" @click-item="clitem2"
              />
            </van-tab>
          </van-tabs>
        </van-dropdown-item>

        <van-dropdown-item :title="brandName" v-model="value1" :options="option1" @change="changebrand"/>

        <van-dropdown-item :title="serName" ref="item3">
          <van-cell-group title="特色功能" :border="false">
            <ul class="service">
              <li v-for="item in service" :key="item.id" :class="[item.id==serviceId?'choose':'']" @click.stop="changeService(item.id)">
                {{item.name}}
              </li>
            </ul>
          </van-cell-group>
          <van-cell-group title="特殊厅" :border="false">
            <ul class="halltype">
              <li v-for="item in hallTypes" :key="item.id" :class="[item.id==hallType?'choose':'']" @click.stop="changeHalltype(item.id)">
                {{item.name}}
              </li>
            </ul>
          </van-cell-group>
          <div class="serBtn">
            <van-button type="default" size="large" round @click.stop="reset">
              重置
            </van-button>
            <van-button type="danger" size="large" round @click.stop="onConfirm">
              确认
            </van-button>
          </div>
        </van-dropdown-item>
      </van-dropdown-menu>

      <div class="cinemaList">
        <ul ref="cinemabox">
          <li v-for="item in cinemaList" :key="item.cinemaId">
            <router-link :to="`/cinemadetial/${item.cinemaId}`">
              <cinema-list :item="item"></cinema-list>
            </router-link>
          </li>
        </ul>
      </div>
      <loading-animation v-if="isload" :showText="true"></loading-animation>

      <div class="locations" v-if="locationData">
        <i class="iconfont icon-location-arrow"></i>{{locationData.district}}{{locationData.detail}}<i class="refalsh iconfont icon-shuaxin" @click.stop="refalsh"></i>
      </div>
      <div class="locations" v-else>
        <i class="iconfont icon-location-arrow"></i>定位失败，请稍后重试<i class="refalsh iconfont icon-shuaxin" @click.stop="refalsh"></i>
      </div>
    </div>

    <div class="wish-movie" v-else-if="active==2">
      <div class="good-movie">
        <list-title v-if="mostExpected">近期最受期待</list-title>
        <ul class="imgBox">
          <li v-for="item in mostExpected" :key="item.id">
            <router-link :to="`/moviedetial/${item.id}`">
              <img-item :item="item" :isWish="true"></img-item>
            </router-link>
          </li>
        </ul>
      </div>
      <div class="bt-line" v-if="mostExpected"></div>
      <ol class="comingList" ref="moviebox" v-if="comingmovie">
        <template v-for="item in coming">
          <div :key="item.time">
            <p class="group-title">
              {{item.time}}
            </p>
            <li v-for="movie in item.items" :key="movie.id">
              <router-link :to="`/moviedetial/${movie.id}`">
                <movie-list :movie="movie" :isComing="true"></movie-list>
              </router-link>
            </li>
          </div>
        </template>
      </ol>
      <div v-else class="err">数据获取失败</div>
      <loading-animation v-if="isload" :showText="true"></loading-animation>
      <div class="bt-line" v-if="newComingmovie && newComingmovie.length>=comingmovieIds.length"></div>
    </div>

    <div v-else class="classic">
      <ol class="classicList" ref="moviebox" v-if="classicmovie && classicmovie.length>0">
        <li v-for="movie in classicmovie" :key="movie.movieId">
          <router-link :to="`/moviedetial/${movie.movieId}`">
            <movie-list :movie="movie" :isClassic="true"></movie-list>
          </router-link>
        </li>
      </ol>
      <div v-else class="err">数据获取失败</div>
      <loading-animation v-if="isload" :showText="true"></loading-animation>
    </div>

    <div class="gotop" v-if="isshow" @click.stop="gotop">
      <i class="iconfont icon-top"></i>
    </div>
  </div>
</template>

<script>
import ListTitle from '../components/ListTitle.vue';
import ImgItem from '../components/ImgItem.vue';
import MovieList from '../components/MovieList.vue'; 
import LoadingAnimation from '@/components/LoadingAnimation.vue';
import _ from 'lodash';
import {mapState,mapGetters,mapActions} from 'vuex'
import CinemaList from '../components/CinemaList.vue';

export default {
  name: 'Home',
  data() {
    return {
      active: 0,
      title:'',
      ratedMovies:null,
      mostExpected:null,
      movieIds:[],
      movieList:[],
      comingmovie:[],
      comingmovieIds:[],
      newComingmovie:[],
      classicmovie:[],
      resultclassic:[],
      page:0,
      isload:true,
      choose:0,
      activeId: -1,
      activeIndex: 0,
      active2Id: -1,
      active2Index: 0,
      items: [],
      items2: [],
      brand:[],
      districtId:-1,
      areaId:-1,
      disName:'',
      lineId:-1,
      stationId:-1,
      areaName:'全城',
      brandName:'品牌',
      value1: -1,
      option1: [],
      service:[],
      hallTypes:[],
      serName:"特色",
      // serIndex:0,
      // hallIndex:0,
      serviceId:-1,
      hallType:-1,
      date:'',
      cinemaPage:0,
      cinemaList:[],
      cinemaCount:0,
      isshow:false,
    };
  },
  created(){
    this.gettopRatedMovies();
    this.getmovieOnInfoList();
    this.getmostExpected();
    this.getComingList();
    this.getclassicMovies();
    let date=new Date();
    let y=date.getFullYear();
    let m=date.getMonth()+1;
    let d=date.getDate();
    m=m>9?m:'0'+m;
    d=d>9?d:'0'+d;
    this.date=y+'-'+m+'-'+d;
  },
  mounted(){
    window.addEventListener("scroll",this.scrollbar);
  },
  beforeDestroy(){
    window.removeEventListener("scroll",this.scrollbar);
  },
  methods:{
    ...mapActions(['resetgeolocation']),
    async gettopRatedMovies(){
      let re=await this.axios.get('index/topRatedMovies');
      this.ratedMovies=re.data.movieList;
      this.title=re.data.title;
      this.isload=false;
    },
    async getmovieOnInfoList(){
      let re=await this.axios.get("index/movieOnInfoList");
      this.movieList=re.data.movieList;
      this.movieIds=re.data.movieIds;
    },
    async getmoreComingList(ids){
      let re=await this.axios.get('index/moreComingList?movieIds='+ids);
      let li=this.movieList;
      li.push(...re.data.coming);
      let b=_.uniqWith(li, _.isEqual);
      this.isload=false;
      this.movieList=b;
    },
    async getmostExpected(){
      let re=await this.axios.get(`index/mostExpected?ci=${this.cityid}&limit=10&offset=0`);
      this.mostExpected=re.data.coming;
    },
    async getComingList(){
      let re=await this.axios.get(`index/comingList?ci=${this.cityid}&limit=10`);
      this.comingmovie=re.data.coming;
      this.comingmovieIds=re.data.movieIds;
    },
    async getmoreList(ids){
      let re=await this.axios.get(`index/moreComingList?ci=${this.cityid}&limit=10&movieIds=${ids}`);
      this.isload=false;
      this.comingmovie.push(...re.data.coming);
    },
    async getclassicMovies(){
      let re=await this.axios.get(`index/moreClassicList?sortId=1&showType=3&limit=10&offset=${this.page*10}`);
      this.resultclassic=re.data;
    },
    async getfilterCinemas(){
      let re=await this.axios.get('index/filterCinemas?ci='+this.cityid);
      this.brand=re.data.brand;
      this.service=re.data.service.subItems;
      this.hallTypes=re.data.hallType.subItems;
      this.cinemaCount=re.data.district.subItems[0].count;
      re.data.district.subItems.forEach(item=>{
        let arr=[];
        item.subItems.forEach(ele=>{
            arr.push({
              text:ele.name+`(${ele.count})`,
              id:ele.id,
              area:ele.name,
              count:ele.count,
              });
        });
        this.items.push(
          { text: `${item.name}(${item.count})`, children:arr,id:item.id,name:item.name,count:item.count}
        )
      });
      if(re.data.subway){
        re.data.subway.subItems.forEach(item=>{
          let arr=[];
          item.subItems.forEach(ele=>{
              arr.push({
                text:ele.name+`(${ele.count})`,
                id:ele.id,
                area:ele.name,
              });
          });
          this.items2.push(
            { text: `${item.name}(${item.count})`, children:arr,id:item.id,count:item.count}
          )
        })
      }
      re.data.brand.subItems.forEach(item=>{
        this.option1.push({
          text:item.name+`(${item.count})`,
          value:item.id,
          name:item.name,
          count:item.count,
          });
      });
    },
    async getmoreCinemas(){
      if(this.locationData){
        let re=await this.axios.get(`index/moreCinemas?day=${this.date}&offset=${this.cinemaPage*20}&limit=20&districtId=${this.districtId}&lineId=${this.lineId}&hallType=${this.hallType}&brandId=${this.value1}&serviceId=${this.serviceId}&areaId=${this.areaId}&stationId=${this.stationId}&item&updateShowDay=true&reqId=1636710166221&cityId=${this.cityid}&lat=${this.locationData.lat}&lng=${this.locationData.lng}`);
        let arr=re.data;
        let a=_.uniqWith(arr, _.isEqual);
        this.isload=false;
        this.cinemaList.push(...a);
      }else{
        let re=await this.axios.get(`index/moreCinemas?day=${this.date}&offset=${this.cinemaPage*20}&limit=20&districtId=${this.districtId}&lineId=${this.lineId}&hallType=${this.hallType}&brandId=${this.value1}&serviceId=${this.serviceId}&areaId=${this.areaId}&stationId=${this.stationId}&item&updateShowDay=true&reqId=1636710166221&cityId=${this.cityid}`);
        let arr=re.data;
        let a=_.uniqWith(arr, _.isEqual);
        this.isload=false;
        this.cinemaList.push(...a);
      }
    },
    scrollbar:_.throttle(function(){
      if(this.$refs.moviebox || this.$refs.cinemabox){
        let el=document.documentElement||document.body;
        let top=el.scrollTop+el.clientHeight;
        let a=el.scrollTop;
        let b=el.clientHeight;
        if(a>b){
          this.isshow=true;
        }else{
          this.isshow=false;
        }
        let moretop=0;
        if(this.$refs.moviebox){
          moretop=this.$refs.moviebox.offsetHeight+this.$refs.moviebox.offsetTop;
        }else{
          moretop=this.$refs.cinemabox.offsetHeight+this.$refs.cinemabox.offsetTop;
        }
        if(top>=moretop+49){
          if(this.active==0 && this.movieList.length<this.movieIds.length){
            this.isload=true;
            this.loadMore();
          }else if(this.active==1 && this.cinemaList.length<this.cinemaCount){
            this.isload=true;
            this.loadMore();
          }else if(this.active==2 && this.newComingmovie.length<this.comingmovieIds.length){
            this.isload=true;
            this.loadMore();
          }else if(this.active==3){
            this.isload=true;
            this.loadMore();
          }else{
            return;
          }
        }
      }else{
        return;
      }
    },300),
    loadMore(){
      switch (this.active) {
        case 0:{
          let num=this.movieIds.length-this.movieList.length;
          let ids=0;
          if(num>10){
            ids=this.movieIds.slice(this.movieList.length,this.movieList.length+10);
          }else{
            ids=this.movieIds.slice(this.movieList.length,this.movieIds.length);
          }
          this.getmoreComingList(ids);
          break;
        }

        case 1:{
          this.cinemaPage++;
          this.getmoreCinemas();
          break;
        }
        
        case 2:{
          let pag=this.comingmovieIds.length-this.newComingmovie.length;
          let sliceIds=0;
          if(pag>10){
            sliceIds=this.comingmovieIds.slice(this.newComingmovie.length,this.comingmovie.length+10);
          }else{
            sliceIds=this.comingmovieIds.slice(this.newComingmovie.length,this.comingmovieIds.length);
          }
          this.getmoreList(sliceIds);
          break;
        }

        case 3:{
          this.page++;
          this.getclassicMovies();
          break;
        }
      
        default:
          break;
      }
    },
    clnav(index){
      this.districtId=this.items[index].id;
      this.lineId=-1;
      this.stationId=-1;
      this.active2Id=-1;
      this.active2Index=0;
      if(this.districtId==-1){
        this.areaName='全城';
        this.activeId=-1;
        this.areaId=-1;
        this.$refs.item1.toggle(false);
        this.cinemaList=[];
        this.isload=true;
        this.getmoreCinemas();
      }else{
        this.disName=this.items[index].name;
      }
      this.cinemaCount=this.items2[index].count;
    },
    clitem(data){
      this.areaId=data.id;
      if(this.areaId==-1){
        this.areaName=this.disName;
      }else{
        this.areaName=data.area;
        this.cinemaCount=data.count;
      }
      this.$refs.item1.toggle();
      this.cinemaList=[];
      this.isload=true;
      this.getmoreCinemas();
    },
    clnav2(index){
      this.activeId=-1;
      this.districtId=-1;
      this.areaId=-1;
      this.activeIndex=0;
      this.lineId=this.items2[index].id;
      if(this.lineId==-1){
        this.areaName='全城';
        this.active2Id=-1;
        this.stationId=-1;
        this.$refs.item1.toggle(false);
        this.cinemaList=[];
        this.isload=true;
        this.isload=true;
        this.getmoreCinemas();
      }else{
        this.disName=this.items2[index].name;
      }
      this.cinemaCount=this.items2[index].count;
    },
    clitem2(data){
      this.stationId=data.id;
      if(this.stationId==-1){
        this.areaName=this.disName;
      }else{
        this.areaName=data.area;
        this.cinemaCount=data.count;
      }
      this.$refs.item1.toggle();
      this.cinemaList=[];
      this.isload=true;
      this.getmoreCinemas();
    },
    changebrand(value){
      if(value==-1){
        this.brandName=this.brand.name;
        this.cinemaCount=this.brand.subItems[0].count;
      }else{
        this.brand.subItems.forEach(item=>{
          if(item.id===value){
            this.brandName=item.name;
            this.cinemaCount=item.count;
          }
        })
      }
      this.cinemaList=[];
      this.isload=true;
      this.getmoreCinemas();
    },
    changeService(id){
      this.serviceId=id;
      this.setTitle();
    },
    changeHalltype(id){
      this.hallType=id;
      this.setTitle();
    },
    setTitle(){
      if(this.serviceId==-1 && this.hallType==-1){
        this.serName='特色';
      }else if(this.serviceId!=-1 && this.hallType==-1){
        this.service.forEach(item=>{
          if(item.id==this.serviceId){
            this.serName=item.name;
          }
        })
      }else if(this.serviceId==-1 && this.hallType!=-1){
        this.hallTypes.forEach(item=>{
          if(item.id==this.hallType){
            this.serName=item.name;
          }
        })
      }else{
        let str='';
        this.service.forEach(item=>{
          if(item.id==this.serviceId){
            str=item.name;
          }
        });
        this.hallTypes.forEach(el=>{
          if(el.id==this.hallType){
            str=str+','+el.name;
          }
        });
        this.serName=str;
      }
    },
    reset(){
      this.serviceId=-1;
      this.hallType=-1;
      this.setTitle();
    },
    onConfirm(){
      this.$refs.item3.toggle();
      this.cinemaList=[];
      this.isload=true;
      this.getmoreCinemas();
    },
    refalsh(){
      this.resetgeolocation();
      this.cinemaList=[];
      this.isload=true;
    },
    gotop(){
      document.documentElement.scrollTop=document.body.scrollTop=0;
    }
  },
  watch:{
    active(){
      document.documentElement.scrollTop=document.body.scrollTop=0;
      this.isshow=false;
      if(this.active==1){
        this.isload=true;
        this.getfilterCinemas();
        this.getmoreCinemas();
      }
    },
    resultclassic(){
      this.isload=false;
      let uniq=_.uniqWith(this.resultclassic, _.isEqual);
      this.classicmovie.push(...uniq);
    },
    locationData(){
      this.getmoreCinemas();
    },
  },
  computed:{
    ...mapState(['city','locationCity']),
    ...mapGetters(['cityid','locationData']),
    coming(){
      let title=[];
      let lis=[];
      let newLi=[];
      this.comingmovie.forEach(item=>{
        let index=title.indexOf(item.comingTitle);
        if(index == -1){
          title.push(item.comingTitle);
        }
      });
      title.forEach(item=>{
        let li=this.comingmovie.filter(ele=>{
          if(ele.comingTitle == item){
            return ele;
          }
        });
        let b=_.uniqWith(li, _.isEqual);
        newLi.push(...b);
        this.newComingmovie=newLi;
        lis.push({
          time:item,
          items:b
        });
      });
      return lis;
    }
  },
  components: {
    ListTitle,
    ImgItem,
    MovieList,
    LoadingAnimation,
    CinemaList,
  }
}
</script>

<style lang="less">
.home{
  &::-webkit-scrollbar{
    display: none;
  }

  .nav{
    position: sticky;
    top: 0;
    left: 0;
    z-index: 2;

    .top{
      background-color: #e54847;
      padding: 6px;
      display: flex;
      height: 38px;
      align-items: center;
      color: #fff;
      
      .logo{
        width: 95px;
      }

      h1{
        text-align: center;
        font-size: 18px;
        flex: 1;
      }

      .nav-botton{
        width: 95px;
        padding-right: 5px;
        text-align: right;

        i{
          font-size: 18px;
        }
      }
    }

    .tab{
      display: flex;
      position: relative;
      padding-bottom: 1px;
      background-color: #fff;

      &::before{
        content: "";
        width: 100%;
        border-top: 1px solid #ddd;
        position: absolute;
        top: 0;
        left: 0;
      }

      &::after{
        content: "";
        width: 100%;
        border-top: 1px solid #ddd;
        position: absolute;
        bottom: 0;
        left: 0;
      }

      .location{
        width: 60px;
        font-size: 13px;
        line-height: 44px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

        span{
          padding-left: 10px;
          color: #999;

        }

        i{
          font-size: 10px;
          padding-left: 3px;
          color: #999;
        }
      }

      .van-tabs{
        flex: 1;

        .van-tab{
          font-weight: 600;
        }
      }

      .search{
        width: 50px;
        text-align: right;
        line-height: 44px;

        i{
          padding-right: 10px;
          font-size: 20px;
          color: #ef4238;
        }
      }
    }
  }
}

.movie,.wish-movie,.classic{
  &::-webkit-scrollbar{
    display: none;
  }
    
  .imgBox{
    // width: 100%;
    padding-top: 5px;
    margin: 0 10px;
    display: flex;
    overflow: hidden;
    overflow-x: scroll;
    &::-webkit-scrollbar{
      display: none;
    }

    li{
      width: 85px;

      &:not(:last-child){
        margin-right: 10px;
      }
    }
  }

  .comingList{
    .group-title{
      font-size: 14px;
      color: #333;
      padding: 12px 10px 0;
    }
  }

  .err{
    line-height: 35px;
    text-align: center;
    font-size: 14px;
    color: #666;
  }

  .bt-line{
    width: 100%;
    height: 10px;
    background-color: #f5f5f5;
  }
}
.classic{
  padding-top: 5px;
}

.cinema{
  overflow-x: hidden;

  .service,.halltype{
    display: flex;
    flex-wrap: wrap;
    padding-bottom: 10px;

    li{
      line-height: 30px;
      width: 20%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      font-size: 12px;
      text-align: center;
      color: #888;
      border: 1px solid #888;
      border-radius: 3px;
      margin: 10px 0 0 10px;

      &.choose{
        color: red;
        border-color: red;
        background-color: #fcf0f0;
      }
    }
  }

  .serBtn{
    display: flex;
    padding: 10px;
  }

  .locations{
    position: fixed;
    width: 80%;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
    background-color: hsla(0,0%,93.7%,.9);
    color: #666;
    font-size: 13px;
    padding: 0 30px 0 15px;
    line-height: 35px;
    border-radius: 8px 8px 0 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;

    i{
      font-size: 12px;
      padding-right: 5px;

      &.refalsh{
        font-size: 14px;
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
      }
    }
  }
}

.gotop{
  position: fixed;
  color: #999;
  bottom: 20%;
  right: 25px;
  background-color: #ddd;
  border-radius: 50%;
  width: 30px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  opacity: .7;
  i{
    font-size: 25px;
  }
}
</style>